<?php

/**
 * Contains a class to display /admin/categories.php.
 *
 * PHP Version 5
 *
 * @category BuyLocal
 * @package  BuyLocal
 * @author   Spencer Hakim <hakims@rpi.edu>
 * @license  http://opensource.org/licenses/gpl-license.php GNU Public License
 * @link     http://code.google.com/p/buylocalopensourcerensselaer/
 */

/** @uses valueOf For safe handling of arrays. */
require_once 'function_valueof.php';
 
/**
 * A class to display /admin/categories.php.
 *
 * @category BuyLocal
 * @package  BuyLocal
 * @author   Spencer Hakim <hakims@rpi.edu>
 * @license  http://opensource.org/licenses/gpl-license.php GNU Public License
 * @link     http://code.google.com/p/buylocalopensourcerensselaer/
*/ 
class PageAdminCategories extends Page
{
    /**
     * State variable for whether or not to update the categories.
     *
     * @access private
     * @var bool
     */
    private $_updateCategories;
    
    /**
     * A variable to contain an error message to be displayed.
     *
     * @access public
     * @var string
     */
    public $error;
    
    /**
     * Constructor function.  Calls the parent constructor and sets the title.
     */
    public function __construct()
    {
        parent::__construct();
        parent::setTitle('Manage Categories');
        
        if (count($_POST) > 0) {
            $this->_updateCategories = true;
        }
    }

    /**
     * Function to print the parent category dropdown box.
     *
     * @param int $parentId The categoryId of the category's parent.
     * @param int $catId    The categoryId for which we are printing.
     * @param int $class    The CSS class to use for coloring.
     *
     * @access private
     * @return null
     */
    private function _printParentDropdown($parentId, $catId, $class)
    {
        $categories = $this->db->getCategories(true);
        
        echo '    <select  name="parent', encode($catId),'" class="', $class, '">',
            "\n",
            '     <option value="0">---</option>', "\n";
        foreach ($categories as $cat) {
            if ($catId == $cat['id']) {
                continue;
            }
            
            if ($parentId == $cat['id']) {
                echo '     <option value="', encode($cat['id']),
                    '" selected="selected">';
            } else {
                echo '     <option value="', encode($cat['id']), '">';
            }

            echo encode($cat['name']), '</option>', "\n";
        }
        echo '    </select>', "\n";
    }
    
    /**
     * Function to print the edit form.
     *
     * @access private
     * @return null
     */
    private function _printEditForm()
    {
        $categories = $this->db->getCategories(true);
        $toggle     = 'Odd';
        
        echo ' <form method="post" action="">', "\n",
            ' <table class="catTable" summary="Editable list of categories.">', "\n";
        foreach ($categories as $cat) {
            echo '  <tr class="catRow', $toggle, '">', "\n",
                '   <td><input type="text" name="name', encode($cat['id']),'" ',
                'value="', encode($cat['name']), '" class="catRow', $toggle,
                '" /></td>', "\n",
                '   <td><input type="text" name="desc', encode($cat['id']),'" ',
                'value="', encode($cat['description']), '" class="catRow', $toggle,
                '" /></td>', "\n",
                '   <td>', "\n",
                $this->_printParentDropdown(
                    $cat['parent'], $cat['id'], 'catRow' . $toggle
                ),
                '   </td>', "\n",
                '   <td><a href="?action=delete&amp;id=', encode($cat['id']),
                '" onclick="',
                'return confirm(\'Are you sure you wish to delete this category?\')',
                '">X</a></td>', "\n",
                '  </tr>', "\n";
            
            if ($toggle == 'Odd') {
                $toggle = 'Even';
            } else {
                $toggle = 'Odd';
            }
        }
        echo ' </table>', "\n",
            ' <div>', "\n",
            '  <input type="submit" class="button" value="Update" />', "\n",
            '  <input type="button" class="button" value="Add New" onclick="',
            'window.location=\'?action=add\'"/>', "\n",
            ' </div>', "\n",
            ' </form>', "\n";
    }
    
    /**
     * Function to print an INPUT form field.
     *
     * @param string $id        The value to use for the id and name fields.
     * @param string $label     The string to insert between the <label> tags.
     * @param string $type      The type of the input field (text, password).
     * @param string $maxlength The maximum length for the input field.
     * @param string $value     The string to insert into the value attribute.
     *
     * @access private
     * @return null
     */
    private function _printFormField($id, $label, $type, $maxlength, $value)
    {
        echo '  <div>', "\n",
            '   <label for="', $id, '">', $label, ':</label>', "\n",
            '   <input id="', $id, '" name="', $id, '" type="', $type, '" ',
            'maxlength="', $maxlength, '" value="', $value, '" />', "\n",
            '  </div>', "\n";
    }

    /**
     * Function to print the edit form.
     *
     * @access private
     * @return null
     */
    private function _printAddForm()
    {
        echo ' <form id="newcategory" method="post" action="">', "\n",
            '  <h2>New Category:</h2>', "\n";
        $this->_printFormField(
            'name', 'Name', 'text', 50, valueOf($_POST, 'name')
        );
        $this->_printFormField(
            'desc', 'Description', 'text', 500, valueOf($_POST, 'desc')
        );
        echo '  <div>', "\n",
            '   <label for="parent">Parent</label>', "\n";
        $this->_printParentDropdown(null, null, null);
        echo '  </div>', "\n";
        echo '  <div>', "\n",
            '   <input type="submit" value="Add" class="button" />', "\n",
            '  </div>', "\n",
            ' </form>', "\n";
    }
    
    /**
     * Processes Categories update.
     *
     * @access private
     * @return null
     */
    private function _update()
    {
        $categories = $this->db->getCategories(true);
        
        foreach ($categories as $cat) {
            $name        = valueOf($_POST, 'name'.$cat['id']);
            $description = valueOf($_POST, 'desc'.$cat['id']);
            $parent      = (int)valueOf($_POST, 'parent'.$cat['id']);

            $this->db->updateCategory(
                new Category($cat['id'], $name, $description, $parent)
            );
        }
    }

    /**
     * Processes new Category.
     *
     * @access private
     * @return null
     */
    private function _add()
    {
        $name        = valueOf($_POST, 'name');
        $description = valueOf($_POST, 'desc');
        $parent      = (int)valueOf($_POST, 'parent');

        $this->db->addCategory(new Category(null, $name, $description, $parent));
    }
    
    /**
     * Function to display the page.
     *
     * @access public
     * @return null
     */
    public function display()
    {
        parent::printHeader();
        if ($this->user->role == R_ADMIN) {
            if (valueOf($_GET, 'action') == 'delete') {
                $this->db->deleteCategory((int)valueOf($_GET, 'id'));
            }
            
            if (valueOf($_GET, 'action') == 'add') {
                if ($this->_updateCategories) {
                    $this->_add();
                    $this->_printEditForm();
                    
                } else {
                    $this->_printAddForm();
                }
                
            } else {
                if ($this->_updateCategories) {
                    $this->_update();
                }
                
                $this->_printEditForm();
            }
        } else {
            echo "You do not have permission to access this page.";
        }
        parent::printFooter();
    }
}

?>